package com.hndzyu.yd.home;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.hndzyu.yd.R;
import com.hndzyu.yd.bean.UserBean;
import com.hndzyu.yd.url.Path;
import com.hndzyu.yd.utils.OkHttpDownloadJsonUtil;
import com.hndzyu.yd.utils.Util;
import com.hndzyu.yd.widget.CodePopupWindow;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

public class InvitationActivity extends AppCompatActivity {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.iv_no)
    ImageView ivNo;
    @BindView(R.id.tv_yaoqing)
    TextView tvYaoqing;
    @BindView(R.id.tv_wode)
    TextView tvWode;
    @BindView(R.id.ll_invite)
    LinearLayout llInvite;
    @BindView(R.id.friend)
    LinearLayout friend;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @BindView(R.id.iv_ewm)
    ImageView iv_ewm;
    @BindView(R.id.tv_jiangli)
    TextView tvJiangli;

    private InvitationAdapter mAdapter;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invitation);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .transparentBar()
                .init();
        initData();
    }

    private void initData() {
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        dialog.setCancelable(true);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        dialog.setMessage("正在生成...Loading");
        tvJiangli.setText((Html.fromHtml("    邀请一位好友,奖励" + "<font color=\"#4474f6\">3元</font>  <br>同时享受好友任务分成")));
        recycler.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new InvitationAdapter(this);
        recycler.setAdapter(mAdapter);
        inviteFriends(UserBean.uid);
        iv_ewm.setImageBitmap(Util.encodeAsBitmap(Path.zxb_register(UserBean.ip, UserBean.uid)));
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(500);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                Util.saveBitmap(InvitationActivity.this, getBitmapByView(rl), "/invite.jpg");
//
//            }
//        }).start();
    }

    @OnClick({R.id.iv_close, R.id.tv_yaoqing, R.id.tv_wode, R.id.wx, R.id.pyq, R.id.ewm})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.iv_close:
                finish();
                break;
            case R.id.tv_yaoqing:
                tvYaoqing.setTextColor(getResources().getColor(R.color.colorAccent));
                tvWode.setTextColor(getResources().getColor(R.color.black));
                llInvite.setVisibility(View.VISIBLE);
                friend.setVisibility(View.GONE);
                break;
            case R.id.tv_wode:
                tvYaoqing.setTextColor(getResources().getColor(R.color.black));
                tvWode.setTextColor(getResources().getColor(R.color.colorAccent));
                llInvite.setVisibility(View.GONE);
                friend.setVisibility(View.VISIBLE);
                break;
            case R.id.wx:
                dialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = getBitmapByView(rl);
                        File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test");
                        if (appDir.exists()) {
                            appDir.delete();
                        } else {
                            appDir.mkdir();
                        }
                        File file = new File(appDir, "/invite.jpg");
//                if (file.exists()) {
//                    file.delete();
//                }
                        FileOutputStream out;
                        try {
                            out = new FileOutputStream(file);
                            if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                                out.flush();
                                out.close();
                                Uri uri = Uri.fromFile(file);
                                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                Wechat.ShareParams sp = new Wechat.ShareParams();
                                sp.setImagePath(Environment.getExternalStorageDirectory() + "/test/invite.jpg");
                                sp.setShareType(Platform.SHARE_IMAGE);
                                Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
                                weChat.share(sp);
                            }
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();


                //微信
                break;
            case R.id.pyq:
                dialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = getBitmapByView(rl);
                        File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test");
                        if (appDir.exists()) {
                            appDir.delete();
                        } else {
                            appDir.mkdir();
                        }
                        File file = new File(appDir, "/invite.jpg");
//                if (file.exists()) {
//                    file.delete();
//                }
                        FileOutputStream out;
                        try {
                            out = new FileOutputStream(file);
                            if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                                out.flush();
                                out.close();
                                Uri uri = Uri.fromFile(file);
                                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                Platform.ShareParams weM = new Platform.ShareParams();
                                weM.setImagePath(Environment.getExternalStorageDirectory() + "/test/invite.jpg");
                                weM.setShareType(Platform.SHARE_IMAGE);
                                Platform WechatM = ShareSDK.getPlatform(WechatMoments.NAME);
                                WechatM.share(weM);
                            }
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();


                break;
            case R.id.ewm:
                CodePopupWindow popupWindow = new CodePopupWindow(this);
                popupWindow.showDown(recycler);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void inviteFriends(int uid) {
        OkHttpDownloadJsonUtil.downloadJson(InvitationActivity.this, Path.inviteFriends + "?uid=" + uid, new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        Gson gson = new Gson();
                        InviteFriend tiBean = gson.fromJson(json, InviteFriend.class);
                        if (tiBean.getData().size() > 0) {
                            mAdapter.updateData(tiBean.getData());
                        } else {
                            ivNo.setVisibility(View.VISIBLE);
                            recycler.setVisibility(View.GONE);
                        }
                    } catch (Exception e) {
                        Toast.makeText(InvitationActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(InvitationActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private Bitmap getBitmapByView(View headerView) {
        int h = headerView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(headerView.getWidth(), h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        headerView.draw(canvas);
        return bitmap;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }


}
